package cn;


import cn.webrx.mapper.DbMapper;
import com.baomidou.mybatisplus.core.MybatisPlusVersion;
import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.File;

@Slf4j
public class Demo {
    SqlSessionFactory sf;
    SqlSession ss;

    @BeforeEach
    public void init() {
        TransactionFactory tx = new JdbcTransactionFactory();

        //mybatis 内置数据库连接池组合
        PooledDataSource ds = new PooledDataSource();
        ds.setUsername("root");
        ds.setDriver("com.mysql.cj.jdbc.Driver");
        ds.setPassword("");
        ds.setUrl("jdbc:mysql://:3305/db");

        Environment env = new Environment("development", tx, ds);

        Configuration cfg = new Configuration(env);

        cfg.addMappers("cn.webrx.mapper");
        //默认会自动加载cn.webrx.mapper.XxxMapper.xml文件
        //批量加载/resources/mapper/*.xml
        var xml = "mapper/";
        var p = Thread.currentThread().getContextClassLoader().getResource(xml).getPath();
        var f = new File(p);
        for (String s : f.list()) {
            var t = xml + s;
            var is = Thread.currentThread().getContextClassLoader().getResourceAsStream(t);
            new XMLMapperBuilder(is, cfg, t, cfg.getSqlFragments()).parse();
        }

        sf = new MybatisSqlSessionFactoryBuilder().build(cfg);
        ss = sf.openSession(true);
    }

    @AfterEach
    public void close() {
        ss.close();
    }

    @Test
    public void query() {
        DbMapper dm = ss.getMapper(DbMapper.class);
        log.info(dm.ver());
        log.info("{}", dm.dbs());
    }

    @Test
    public void t() {
        log.info("hello world");
    }

    @Test
    public void ver() {
        System.out.println(MybatisPlusVersion.getVersion());
    }
}
